/**
 * 
 */
package com.evolvedb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Mike
 *
 */
public class EVDB {
	Logger log = LoggerFactory.getLogger(EVDB.class);
	private HashMap<String, String> config = new HashMap<String, String>();
	// Change file buffer. The files we have are around this size or less
	static final byte[] buffer = new byte[32000];
	
	public EVDB(HashMap<String, String> config) {
		this.config = config;
		config.put("version", "5");
		
		loadChangeFiles();
	}
	
	// Debugging only
	public static void main(String[] args) {
		HashMap<String, String> cfg = new HashMap<String, String>();
		cfg.put("changes-home", "src/test/resources/changes");
		EVDB app = new EVDB(cfg);
	}
	
	// Show pending changes
	public void status() {
		
	}
	
	public void update() {
		// Check passed in version
		// Build list of changes from files
		
	}
	
	public void outputSQL() {
		
	}
	
	
	private void loadChangeFiles() {
		File[] files = new File(config.get("changes-home")).listFiles();
		
		// Discover all of the version directories
		ArrayList<DottedVersion> versions = new ArrayList<DottedVersion>();
		for (File f : files) {
			if (f.isDirectory() && !f.isHidden()) {
				try {
					versions.add(new DottedVersion(f.getName()));
				} catch (InvalidVersionException e) {
					throw new RuntimeException("Changes directory "+f.getName()+" is an invalid version.");
				}
			}
		}
		// Sort them in order
		Collections.sort(versions);
		
		// Read in the files
		for (DottedVersion v : versions) {
			File file = new File(config.get("changes-home"), v.getVersion()+"/changes.sql");
			if (file.exists() && file.canRead()) {
				try {
					// TODO: create a parser for these and store them in a list
					System.out.println(readFile(file));
					// if it starts with --
						// check if it starts with evdb
					
					
				} catch (Exception e) {
					throw new RuntimeException("File "+file.getPath()+ " couldn't be read.", e);
				}				
			}
		}
	}
	
	private String readFile(File file) throws FileNotFoundException, IOException {
		// Lets make this an 'efficient' read because... well, its fun
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			StringBuilder content = new StringBuilder();
			while (in.read(buffer) != -1) {
				content.append(new String(buffer));
			}
			
			return content.toString();
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}
	
}
